package jwei.apps.indextank;

import java.util.HashMap;
import java.util.Map;

import jwei.apps.indextank.client.IndexTankClient;
import jwei.apps.indextank.client.IndexTankClient.Index;
import jwei.apps.indextank.db.RestaurantDb;
import jwei.apps.indextank.objects.Constants;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.util.Linkify;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class RestaurantDetailsActivity extends Activity {

    private ProgressDialog pd;

    private TextView nameTv, addrTv, phoneTv, tagsTv, dishesTv, ingredientsTv;

    private Button bookmarkButton, webButton;

    private Button addTags, addDishes, addIngredients;

    private String docid, name, street, city, state, zip, url, phone, tags, dishes, ingredients;

    private final int ADD_TAG = 0;

    private final int ADD_DISH = 1;

    private final int ADD_INGREDIENT = 2;

    private Button submitTag, submitDish, submitIng;

    private EditText tagText, dishText, ingText;

    private Dialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.restaurant_details_layout);

        nameTv = (TextView) findViewById(R.id.details_name);
        addrTv = (TextView) findViewById(R.id.details_address);
        phoneTv = (TextView) findViewById(R.id.details_phone);
        tagsTv = (TextView) findViewById(R.id.details_tags);
        dishesTv = (TextView) findViewById(R.id.details_dishes);
        ingredientsTv = (TextView) findViewById(R.id.details_ingredients);

        bookmarkButton = (Button) findViewById(R.id.add_to_bookmarks);
        webButton = (Button) findViewById(R.id.restaurant_browser);

        addTags = (Button) findViewById(R.id.add_tags);
        addDishes = (Button) findViewById(R.id.add_dishes);
        addIngredients = (Button) findViewById(R.id.add_ingredients);

        Intent i = getIntent();
        docid = i.getStringExtra("docid");
        name = i.getStringExtra("name");
        street = i.getStringExtra("street");
        city = i.getStringExtra("city");
        state = i.getStringExtra("state");
        zip = i.getStringExtra("zip");
        url = i.getStringExtra("url");
        phone = i.getStringExtra("phone");
        tags = i.getStringExtra("tags");
        dishes = i.getStringExtra("dishes");
        ingredients = i.getStringExtra("ingredients");

        nameTv.setText(name);
        addrTv.setText(street + ", " + city + ", " + state + " " + zip);
        Linkify.addLinks(addrTv, Linkify.MAP_ADDRESSES);
        phoneTv.setText(phone);
        Linkify.addLinks(phoneTv, Linkify.PHONE_NUMBERS);

        if (url.equals("")) {
            webButton.setVisibility(View.INVISIBLE);
        } else {
            webButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setData(Uri.parse(url));
                    startActivity(i);
                }

            });
        }

        bookmarkButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                RestaurantDb rdb = RestaurantDb.getInstance();
                int curStatus = rdb.getRestaurantQueueStatus(getContentResolver(), docid);
                if (curStatus > 0) {
                    rdb.updateRestaurantQueue(getContentResolver(), docid, 0);
                    bookmarkButton.setBackgroundResource(R.drawable.bookmark_icon_selector);
                    Toast t = Toast.makeText(RestaurantDetailsActivity.this, "Removed restaurant from your bookmarks.",
                            Toast.LENGTH_SHORT);
                    t.show();
                } else {
                    rdb.updateRestaurantQueue(getContentResolver(), docid, 1);
                    bookmarkButton.setBackgroundResource(R.drawable.trash_can_selector);
                    Toast t = Toast.makeText(RestaurantDetailsActivity.this, "Added restaurant to your bookmarks!",
                            Toast.LENGTH_SHORT);
                    t.show();
                }
            }

        });

        tagsTv.setText(tags);
        dishesTv.setText(dishes);
        ingredientsTv.setText(ingredients);

        addTags.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                showDialog(ADD_TAG);
            }

        });

        addDishes.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                showDialog(ADD_DISH);
            }

        });

        addIngredients.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                showDialog(ADD_INGREDIENT);
            }

        });

        RestaurantDb rdb = RestaurantDb.getInstance();
        int curStatus = rdb.getRestaurantQueueStatus(getContentResolver(), docid);
        if (curStatus > 0) {
            bookmarkButton.setBackgroundResource(R.drawable.trash_can_selector);
        }
    }

    protected Dialog onCreateDialog(int id) {
        final RestaurantDb rdb = RestaurantDb.getInstance();
        switch (id) {
            case ADD_TAG:
                dialog = new Dialog(RestaurantDetailsActivity.this);

                dialog.setContentView(R.layout.add_tags_dialog);
                dialog.setTitle("Add a Tag");

                tagText = (EditText) dialog.findViewById(R.id.add_tags_text);
                submitTag = (Button) dialog.findViewById(R.id.submit_tags);
                submitTag.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        String tag = tagText.getText().toString();
                        if (tag.equals("")) {
                            Toast t = Toast.makeText(RestaurantDetailsActivity.this, "Please type a tag!",
                                    Toast.LENGTH_SHORT);
                            t.show();
                        } else {
                            String cur = tagsTv.getText().toString();
                            if (cur.equals("")) {
                                cur += tag.replace(",", "");
                            } else {
                                // strip all commas first
                                cur += ", " + tag.replace(",", "");
                            }
                            // reset the tags text view
                            tagsTv.setText(cur);
                            tags = cur;

                            // update in cache
                            rdb.updateRestaurantTags(getContentResolver(), docid, cur);

                            // update the document in the index
                            new UpdateIndexTask().execute(docid);

                            tagText.setText("");
                            dialog.dismiss();
                        }

                    }

                });
                break;
            case ADD_DISH:
                dialog = new Dialog(RestaurantDetailsActivity.this);

                dialog.setContentView(R.layout.add_dishes_dialog);
                dialog.setTitle("Add a Dish");

                dishText = (EditText) dialog.findViewById(R.id.add_dishes_text);
                submitDish = (Button) dialog.findViewById(R.id.submit_dishes);
                submitDish.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        String dish = dishText.getText().toString();
                        if (dish.equals("")) {
                            Toast t = Toast.makeText(RestaurantDetailsActivity.this, "Please type a dish!",
                                    Toast.LENGTH_SHORT);
                            t.show();
                        } else {
                            String cur = dishesTv.getText().toString();
                            if (cur.equals("")) {
                                cur += dish.replace(",", "");
                            } else {
                                // strip all commas first
                                cur += ", " + dish.replace(",", "");
                            }
                            // reset the dishes text view
                            dishesTv.setText(cur);
                            dishes = cur;

                            // update in cache
                            rdb.updateRestaurantDishes(getContentResolver(), docid, cur);

                            // update the document in the index
                            new UpdateIndexTask().execute(docid);

                            dishText.setText("");
                            dialog.dismiss();
                        }

                    }

                });
                break;
            case ADD_INGREDIENT:
                dialog = new Dialog(RestaurantDetailsActivity.this);

                dialog.setContentView(R.layout.add_ingredients_dialog);
                dialog.setTitle("Add an Ingredient");

                ingText = (EditText) dialog.findViewById(R.id.add_ingredients_text);
                submitIng = (Button) dialog.findViewById(R.id.submit_ingredient);
                submitIng.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        String ing = ingText.getText().toString();
                        if (ing.equals("")) {
                            Toast t = Toast.makeText(RestaurantDetailsActivity.this, "Please type an ingredient!",
                                    Toast.LENGTH_SHORT);
                            t.show();
                        } else {
                            String cur = ingredientsTv.getText().toString();
                            if (cur.equals("")) {
                                cur += ing.replace(",", "");
                            } else {
                                // strip all commas first
                                cur += ", " + ing.replace(",", "");
                            }
                            // reset the dishes text view
                            ingredientsTv.setText(cur);
                            ingredients = cur;

                            // update in cache
                            rdb.updateRestaurantIngredients(getContentResolver(), docid, cur);

                            // update the document in the index
                            new UpdateIndexTask().execute(docid);

                            ingText.setText("");
                            dialog.dismiss();
                        }

                    }

                });
                break;
            default:
                dialog = null;
        }
        return dialog;
    }

    private class UpdateIndexTask extends AsyncTask<String, String, Integer> {

        @Override
        protected void onPreExecute() {
            pd = ProgressDialog.show(RestaurantDetailsActivity.this, "Updating IndexTank",
                    "Please wait while we update our database...", true, false);
        }

        // param[0] is the docid
        protected Integer doInBackground(String... param) {
            IndexTankClient client = new IndexTankClient(Constants.INDEX_URL);
            Index index = client.getIndex(Constants.INDEX_NAME);

            try {
                Map<String, String> fields = new HashMap<String, String>();
                fields.put("name", name);
                fields.put("address", street);
                fields.put("city", city);
                fields.put("state", state);
                fields.put("postcode", zip);
                fields.put("telephone", phone);
                fields.put("website", url);

                // note that these tags / dishes / ingredients should be updated
                fields.put("tags", tags);
                fields.put("dishes", dishes);
                fields.put("ingredients", ingredients);
                index.addDocument(param[0], fields);
                return 1;
            } catch (Exception e) {
                e.printStackTrace();
                return -1;
            }
        }

        protected void onProgressUpdate(String... progress) {
            pd.setMessage(progress[0]);
        }

        protected void onPostExecute(Integer results) {
            if (results > 0) {
                Toast t = Toast.makeText(RestaurantDetailsActivity.this, "Restaurant updated!", Toast.LENGTH_SHORT);
                t.show();
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            } else {
                Toast t = Toast.makeText(RestaurantDetailsActivity.this,
                        "Sorry - couldn't update this restaurant at this time!", Toast.LENGTH_SHORT);
                t.show();
            }
            if (pd.isShowing()) {
                pd.dismiss();
            }
        }
    }

}
